from django.shortcuts import render
from django.http import JsonResponse
from django.conf import settings
from user.dataCheck import DataCheck
from need.models import SoftwareNeed, NeedHandle
from software.models import Software, SoftwareVersion
from announcement.models import Announcement
import pdb, os
import logging
from software.views.view_download import download
from conf.sysConfig import config

tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")
datacheck = DataCheck()


def getNeedList(request, *args, **kwargs):
    """
        inputData:{
            token:data.token,//用户密钥
            page:data.page,
            maxItem:data.maxItem,
            softwareId:data.softwareId,//仓库id
            needState:data.needState,//管理人员:0：未处理，1：已处理，2：驳回，3：归档（删除）
                                    //使用人员:0未处理,1已处理  
                                    //开发人员:0：未处理，1：已处理，2：驳回
            
        },
        resData:{
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
            'totalNum':null,//检索到总条数
            'needlist':[{
                'softwarename':null,
                'iconUrl':null,//软件图标
                'needId':null,//需求Id
                'storehouse':null,//仓库名称
                'version':null,//软件版本
                'userName':null,//提报人
                'warZone':null,//战区
                'company':null,//单位
                'raiseTime':null,//提报时间
                'title':null,//需求标题
                'needContent':null,//需求内容
                'examineState':null,//需求状态
                'needResult':null,//驳回理由
                'handleContent':null,//解决方案

                'dealName':null,//回复人
                'dealTime':null,//解决时间
            }]
        }
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    # 从数据库获取软件时的filter条件字典
    filterDict = {}
    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    if requestParam['needState'] != '':
        if requestParam['needState'] == '0':
            if userType == '1':
                filterDict['isActive'] = True
                filterDict['ishandle'] = False
                filterDict['isExamine'] = True
                filterDict['examineState'] = '1'
            elif userType == '2':
                filterDict['isActive'] = True
                filterDict['ishandle'] = False
                filterDict['isExamine'] = False
                filterDict['examineState'] = '0'
            elif userType == '3':
                filterDict['isActive'] = True
                filterDict['ishandle'] = False
            else:
                data = {
                    "code": 1,
                    "msg": "userType Error",
                    'totalNum': 0,
                    'materialList': []
                }
                logger_request.info(data)
                return JsonResponse(data)
        elif requestParam['needState'] == '1':
            filterDict['ishandle'] = True
            filterDict['isActive'] = True
            filterDict['isExamine'] = True
            filterDict['examineState'] = '1'
        elif requestParam['needState'] == '2':
            filterDict['ishandle'] = True
            filterDict['isActive'] = True
            filterDict['isExamine'] = True
            filterDict['examineState'] = '2'
        elif requestParam['needState'] == '3':
            filterDict['isActive'] = False
        else:
            data = {
                "code": 0,
                "msg": "state Error",
                'totalNum': 0,
                'materialList': []
            }
            logger_request.info(data)
            return JsonResponse(data)
    if requestParam['softwareVersionId'] != None:
        filterDict['softwareVersion__id'] = requestParam['softwareVersionId']  ##后期改成版本
    # pdb.set_trace()
    needlist = SoftwareNeed.objects.filter(**filterDict).order_by('-createTime')
    if needlist.exists():
        needLists = []
        totalNum = len(needlist)
        for need in needlist:
            if requestParam['needState'] == '0':
                needlist = {
                    'softwareName': need.softwareVersion.softwareName,
                    'iconUrl': download(need.softwareVersion.logo.fileName, 'logo',
                                        need.softwareVersion.logo.filePath)[1],
                    'needId': need.id,
                    'storehouseName': need.softwareVersion.store.storehouseName,
                    'version': need.softwareVersion.version,
                    'name': need.user.name,
                    'warZone': need.user.warZone.name,
                    'company': need.user.company.name,
                    'raiseTime': need.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'title': need.title,
                    'needContent': need.needContent,
                    'examineState': need.examineState,
                    'needResult': '',
                    'handleContent': '',
                    'dealName': '',
                    'dealTime': '',
                }
                needLists.append(needlist)
            elif requestParam['needState'] == '1':
                handle = NeedHandle.objects.filter(need=need).first()
                needlist = {
                    'softwareName': need.softwareVersion.softwareName,
                    'iconUrl': download(need.softwareVersion.logo.fileName, 'logo',
                                        need.softwareVersion.logo.filePath)[1],
                    'needId': need.id,
                    'storehouseName': need.softwareVersion.store.storehouseName,
                    'version': need.softwareVersion.version,
                    'name': need.user.name,
                    'warZone': need.user.warZone.name,
                    'company': need.user.company.name,
                    'raiseTime': need.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'title': need.title,
                    'needContent': need.needContent,
                    'examineState': need.examineState,
                    'needResult': '',
                    'handleContent': handle.handleContent,
                    'dealName': handle.user.name,
                    'dealTime': handle.handleTime.strftime('%Y-%m-%d %H:%M:%S'),
                }
                needLists.append(needlist)
            elif requestParam['needState'] == '2':
                reject = NeedHandle.objects.filter(need=need).first()
                needlist = {
                    'softwareName': need.softwareVersion.softwareName,
                    'iconUrl': download(need.softwareVersion.logo.fileName, 'logo',
                                        need.softwareVersion.logo.filePath)[1],
                    'needId': need.id,
                    'storehouseName': need.softwareVersion.store.storehouseName,
                    'version': need.softwareVersion.version,
                    'name': need.user.name,
                    'warZone': need.user.warZone.name,
                    'company': need.user.company.name,
                    'raiseTime': need.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'title': need.title,
                    'needContent': need.needContent,
                    'examineState': need.examineState,
                    'needResult': reject.rejectResult,
                    'handleContent': '',
                    'dealName': reject.user.name,
                    'dealTime': reject.handleTime.strftime('%Y-%m-%d %H:%M:%S'),
                }
                needLists.append(needlist)
            elif requestParam['needState'] == '3':
                if need.ishandle == False:
                    needlist = {
                        'softwareName': need.softwareVersion.softwareName,
                        'iconUrl': download(need.softwareVersion.logo.fileName, 'logo',
                                            need.softwareVersion.logo.filePath)[1],
                        'needId': need.id,
                        'storehouseName': need.softwareVersion.store.storehouseName,
                        'version': need.softwareVersion.version,
                        'name': need.user.name,
                        'warZone': need.user.warZone.name,
                        'company': need.user.company.name,
                        'raiseTime': need.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'title': need.title,
                        'needContent': need.needContent,
                        'needState': need.needState,
                        'needResult': '',
                        'handleContent': '',
                        'dealName': '',
                        'dealTime': '',
                    }
                    needLists.append(needlist)
                elif need.ishandle == True and need.isExamine == True and need.examineState == '1':
                    handle = NeedHandle.objects.filter(need=need).first()
                    needlist = {
                        'softwareName': need.softwareVersion.softwareName,
                        'iconUrl': download(need.softwareVersion.logo.fileName, 'logo',
                                            need.softwareVersion.logo.filePath)[1],
                        'needId': need.id,
                        'storehouseName': need.softwareVersion.store.storehouseName,
                        'version': need.softwareVersion.version,
                        'name': need.user.name,
                        'warZone': need.user.warZone.name,
                        'company': need.user.company.name,
                        'raiseTime': need.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'title': need.title,
                        'needContent': need.needContent,
                        'needState': need.needState,
                        'needResult': '',
                        'handleContent': handle.handleContent,
                        'dealName': handle.user.name,
                        'dealTime': handle.handleTime.strftime('%Y-%m-%d %H:%M:%S'),
                    }
                    needLists.append(needlist)
                elif need.ishandle == True and need.isExamine == True and need.examineState == '2':
                    reject = NeedHandle.objects.filter(need=need).first()
                    needlist = {
                        'softwareName': need.softwareVersion.softwareName,
                        'iconUrl': download(need.softwareVersion.logo.fileName, 'logo',
                                            need.softwareVersion.logo.filePath)[1],
                        'needId': need.id,
                        'storehouseName': need.softwareVersion.store.storehouseName,
                        'version': need.softwareVersion.version,
                        'name': need.user.name,
                        'warZone': need.user.warZone.name,
                        'company': need.user.company.name,
                        'raiseTime': need.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'title': need.title,
                        'needContent': need.needContent,
                        'needState': need.needState,
                        'needResult': reject.rejectResult,
                        'handleContent': '',
                        'dealName': reject.user.name,
                        'dealTime': reject.handleTime.strftime('%Y-%m-%d %H:%M:%S'),
                    }
                    needLists.append(needlist)
        result = needLists[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                    requestParam[
                                                                                                        'page'] *
                                                                                                    requestParam[
                                                                                                        'maxItem'])]

    else:
        data = {
            "code": 0,
            "msg": "success",
            'totalNum': 0,
            'needlist': []
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        'totalNum': totalNum,
        'needlist': result
    }
    logger_request.info(data)
    return JsonResponse(data)


def needScreen(request, *args, **kwargs):
    """
        inputData:{
            token:data.token,//用户密钥
            page:data.page,
            maxItem:data.maxItem,
            warZoneId:data.warZoneId,//战区id
            companyId:data.companyId,//单位id
            storehouseId:data.storehouseId,//仓库id

            key:data.key,//关键词
            needState:data.needState,//管理人员:0：未处理，1：已处理，2：驳回，3：归档（删除）
                                    //使用人员:0未处理,1已处理  
                                    //开发人员:0：未处理，1：已处理，2：驳回
            
        },
        resData:{
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
            'totalNum':null,//检索到总条数
            'needlist':[{
                'softwarename':null,
                'iconUrl':null,//软件图标
                'needId':null,//需求Id
                'storehouse':null,//仓库名称
                'version':null,//软件版本
                'userName':null,//提报人
                'warZone':null,//战区
                'company':null,//单位
                'raiseTime':null,//提报时间
                'title':null,//需求标题
                'needContent':null,//需求内容
                'examineState':null,//需求状态
                'needResult':null,//驳回理由
                'handleContent':null,//解决方案

                'dealName':null,//回复人
                'dealTime':null,//解决时间
            }]
        }
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    # 从数据库获取软件时的filter条件字典
    filterDict = {}
    user = datacheck.getUser(requestParam['token'])
    userType = user.userType

    if requestParam['key'] != '':
        filterDict['softwareVersion__softwareName__icontains'] = requestParam['key']  # to do 关键字描述

    if requestParam['needState'] != '':
        if requestParam['needState'] == '0':
            if userType == '1':
                filterDict['isActive'] = True
                filterDict['ishandle'] = False
                filterDict['isExamine'] = True
                filterDict['examineState'] = '1'
            elif userType == '2':
                filterDict['isActive'] = True
                filterDict['ishandle'] = False
                filterDict['isExamine'] = False
                filterDict['examineState'] = '0'
            elif userType == '3':
                filterDict['isActive'] = True
                filterDict['ishandle'] = False
            else:
                data = {
                    "code": 1,
                    "msg": "userType Error",
                    'totalNum': 0,
                    'materialList': []
                }
                logger_request.info(data)
                return JsonResponse(data)
        elif requestParam['needState'] == '1':
            filterDict['ishandle'] = True
            filterDict['isActive'] = True
            filterDict['isExamine'] = True
            filterDict['examineState'] = '1'
        elif requestParam['needState'] == '2':
            filterDict['ishandle'] = True
            filterDict['isActive'] = True
            filterDict['isExamine'] = True
            filterDict['examineState'] = '2'
        elif requestParam['needState'] == '3':
            filterDict['isActive'] = False
        else:
            data = {
                "code": 1,
                "msg": "state Error",
                'totalNum': 0,
                'materialList': []
            }
            logger_request.info(data)
            return JsonResponse(data)
    if requestParam['storehouseId'] != None:
        filterDict['softwareVersion__software__store__id'] = requestParam['storehouseId']  ##后期改成版本
    if requestParam['warZoneId'] != None:
        filterDict['user__warZone__id'] = requestParam['warZoneId']
        if requestParam['companyId'] != None:
            filterDict['user__company__id'] = requestParam['companyId']
            # pdb.set_trace()
    needlist = SoftwareNeed.objects.filter(**filterDict).order_by('-createTime')
    if needlist.exists():
        needLists = []
        totalNum = len(needlist)
        for need in needlist:
            if requestParam['needState'] == '0':
                needlist = {
                    'softwareName': need.softwareVersion.softwareName,
                    'iconUrl': download(need.softwareVersion.logo.fileName, 'logo',
                                        need.softwareVersion.logo.filePath)[1],
                    'needId': need.id,
                    'storehouseName': need.softwareVersion.store.storehouseName,
                    'version': need.softwareVersion.version,
                    'name': need.user.name,
                    'warZone': need.user.warZone.name,
                    'company': need.user.company.name,
                    'raiseTime': need.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'title': need.title,
                    'needContent': need.needContent,
                    'examineState': need.examineState,
                    'needResult': '',
                    'handleContent': '',
                    'dealName': '',
                    'dealTime': '',
                }
                needLists.append(needlist)
            elif requestParam['needState'] == '1':
                handle = NeedHandle.objects.filter(need=need).first()
                needlist = {
                    'softwareName': need.softwareVersion.softwareName,
                    'iconUrl': download(need.softwareVersion.logo.fileName, 'logo',
                                        need.softwareVersion.logo.filePath)[1],
                    'needId': need.id,
                    'storehouseName': need.softwareVersion.store.storehouseName,
                    'version': need.softwareVersion.version,
                    'name': need.user.name,
                    'warZone': need.user.warZone.name,
                    'company': need.user.company.name,
                    'raiseTime': need.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'title': need.title,
                    'needContent': need.needContent,
                    'examineState': need.examineState,
                    'needResult': '',
                    'handleContent': handle.handleContent,
                    'dealName': handle.user.name,
                    'dealTime': handle.handleTime.strftime('%Y-%m-%d %H:%M:%S'),
                }
                needLists.append(needlist)
            elif requestParam['needState'] == '2':
                reject = NeedHandle.objects.filter(need=need).first()
                needlist = {
                    'softwareName': need.softwareVersion.softwareName,
                    'iconUrl': download(need.softwareVersion.logo.fileName, 'logo',
                                        need.softwareVersion.logo.filePath)[1],
                    'needId': need.id,
                    'storehouseName': need.softwareVersion.store.storehouseName,
                    'version': need.softwareVersion.version,
                    'name': need.user.name,
                    'warZone': need.user.warZone.name,
                    'company': need.user.company.name,
                    'raiseTime': need.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'title': need.title,
                    'needContent': need.needContent,
                    'examineState': need.examineState,
                    'needResult': reject.rejectResult,
                    'handleContent': '',
                    'dealName': reject.user.name,
                    'dealTime': reject.handleTime.strftime('%Y-%m-%d %H:%M:%S'),
                }
                needLists.append(needlist)
            elif requestParam['needState'] == '3':
                if need.ishandle == False:
                    needlist = {
                        'softwareName': need.softwareVersion.softwareName,
                        'iconUrl': download(need.softwareVersion.logo.fileName, 'logo',
                                            need.softwareVersion.logo.filePath)[1],
                        'needId': need.id,
                        'storehouseName': need.softwareVersion.store.storehouseName,
                        'version': need.softwareVersion.version,
                        'name': need.user.name,
                        'warZone': need.user.warZone.name,
                        'company': need.user.company.name,
                        'raiseTime': need.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'title': need.title,
                        'needContent': need.needContent,
                        'needState': need.needState,
                        'needResult': '',
                        'handleContent': '',
                        'dealName': '',
                        'dealTime': '',
                    }
                    needLists.append(needlist)
                elif need.ishandle == True and need.isExamine == True and need.examineState == '1':
                    handle = NeedHandle.objects.filter(need=need).first()
                    needlist = {
                        'softwareName': need.softwareVersion.softwareName,
                        'iconUrl': download(need.softwareVersion.logo.fileName, 'logo',
                                            need.softwareVersion.logo.filePath)[1],
                        'needId': need.id,
                        'storehouseName': need.softwareVersion.store.storehouseName,
                        'version': need.softwareVersion.version,
                        'name': need.user.name,
                        'warZone': need.user.warZone.name,
                        'company': need.user.company.name,
                        'raiseTime': need.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'title': need.title,
                        'needContent': need.needContent,
                        'needState': need.needState,
                        'needResult': '',
                        'handleContent': handle.handleContent,
                        'dealName': handle.user.name,
                        'dealTime': handle.handleTime.strftime('%Y-%m-%d %H:%M:%S'),
                    }
                    needLists.append(needlist)
                elif need.ishandle == True and need.isExamine == True and need.examineState == '2':
                    reject = NeedHandle.objects.filter(need=need).first()
                    needlist = {
                        'softwareName': need.softwareVersion.softwareName,
                        'iconUrl': download(need.softwareVersion.logo.fileName, 'logo',
                                            need.softwareVersion.logo.filePath)[1],
                        'needId': need.id,
                        'storehouseName': need.softwareVersion.store.storehouseName,
                        'version': need.softwareVersion.version,
                        'name': need.user.name,
                        'warZone': need.user.warZone.name,
                        'company': need.user.company.name,
                        'raiseTime': need.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                        'title': need.title,
                        'needContent': need.needContent,
                        'needState': need.needState,
                        'needResult': reject.rejectResult,
                        'handleContent': '',
                        'dealName': reject.user.name,
                        'dealTime': reject.handleTime.strftime('%Y-%m-%d %H:%M:%S'),
                    }
                    needLists.append(needlist)
        result = needLists[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                    requestParam[
                                                                                                        'page'] *
                                                                                                    requestParam[
                                                                                                        'maxItem'])]

    else:
        data = {
            "code": 0,
            "msg": "success",
            'totalNum': 0,
            'needlist': []
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        'totalNum': totalNum,
        'needlist': result
    }
    logger_request.info(data)
    return JsonResponse(data)


def needAnnounce(request, *args, **kwargs):
    """
        inputData:{
            token:data.token,//用户密钥
            noticeId:data.noticeId,//通知Id

            
        },
        resData:{
            'code': null, // 标志返回状态、0：成功 1：失败
            'needlist':[{
                'softwareName':null,//软件名称
                'iconUrl':null,//软件图标
                'needId':null,//需求Id
                'storehouseName':null,//软件所属仓库名称
                'version':null,//软件版本
                'name':null,//提报人
                'warZone':null,
                'company':null,
                //
                //
                'needState':null,////管理人员:0：未处理，1：已处理，2：驳回，3：归档（删除）
                                //使用人员:0未处理,1已处理,2:驳回
                                //开发人员:0：未处理，1：已处理，2：驳回
                //
                'raiseTime':null,//提报时间
                'title':null,//需求标题
                'needContent':null,//需求内容
                'needResult':null,//驳回理由
                'handleContent':null,//解决方案
                'dealName':null,//回复人
                'dealTime':null,//解决时间
        }
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    user = datacheck.getUser(requestParam['token'])

    anno = Announcement.objects.get(pk=requestParam['noticeId'])
    needlist = SoftwareNeed.objects.filter(pk=anno.IdNum)
    needLists = []
    # totalNum = len(needlist)
    for need in needlist:
        handleItem = NeedHandle.objects.filter(need=need)
        if handleItem.exists():
            handle = handleItem[0]
            if need.examineState == '1':
                needlist = {
                    'softwareName': need.softwareVersion.softwareName,
                    'iconUrl': download(need.softwareVersion.logo.fileName, 'logo',
                                        need.softwareVersion.logo.filePath)[1],
                    'needId': need.id,
                    'storehouseName': need.softwareVersion.store.storehouseName,
                    'version': need.softwareVersion.version,
                    'name': need.user.name,
                    'warZone': need.user.warZone.name,
                    'company': need.user.company.name,
                    'raiseTime': need.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'title': need.title,
                    'needContent': need.needContent,
                    'needState': need.needState,
                    'needResult': '',
                    'handleContent': handle.handleContent,
                    'dealName': handle.user.name,
                    'dealTime': handle.handleTime.strftime('%Y-%m-%d %H:%M:%S'),
                }
                needLists.append(needlist)
            elif need.examineState == '2':
                needlist = {
                    'softwareName': need.softwareVersion.softwareName,
                    'iconUrl': download(need.softwareVersion.logo.fileName, 'logo',
                                        need.softwareVersion.logo.filePath)[1],
                    'needId': need.id,
                    'storehouseName': need.softwareVersion.store.storehouseName,
                    'version': need.softwareVersion.version,
                    'name': need.user.name,
                    'warZone': need.user.warZone.name,
                    'company': need.user.company.name,
                    'raiseTime': need.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'title': need.title,
                    'needContent': need.needContent,
                    'needState': need.needState,
                    'needResult': handle.rejectResult,
                    'handleContent': '',
                    'dealName': handle.user.name,
                    'dealTime': handle.handleTime.strftime('%Y-%m-%d %H:%M:%S'),
                }
                needLists.append(needlist)
        else:
            needlist = {
                'softwareName': need.softwareVersion.softwareName,
                'iconUrl': download(need.softwareVersion.logo.fileName, 'logo',
                                    need.softwareVersion.logo.filePath)[1],
                'needId': need.id,
                'storehouseName': need.softwareVersion.store.storehouseName,
                'version': need.softwareVersion.version,
                'name': need.user.name,
                'warZone': need.user.warZone.name,
                'company': need.user.company.name,
                'raiseTime': need.raiseTime.strftime('%Y-%m-%d %H:%M:%S'),
                'title': need.title,
                'needContent': need.needContent,
                'needState': need.needState,
                'needResult': '',
                'handleContent': '',
                'dealName': '',
                'dealTime': '',
            }
            needLists.append(needlist)

    # result = needLists[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
    #                                                                                                 requestParam[
    #                                                                                                     'page'] *
    #                                                                                                 requestParam[
    #                                                                                                     'maxItem'])]    
    data = {
        "code": 0,
        "msg": "success",
        'needlist': needLists
    }
    logger_request.info(data)
    return JsonResponse(data)
